import requests
import json
import hashlib
import time
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import base64
import binascii


def generate_signature(params):
    """
    生成API签名
    """
    # 1. 清理空值参数
    cleaned_params = {}
    for key, value in params.items():
        if value != "" and value is not None:
            cleaned_params[key] = value

    # 2. 按键名排序并拼接参数字符串
    # Python中使用sorted配合key参数实现排序
    sorted_keys = sorted(cleaned_params.keys(), key=lambda x: x.upper())

    param_string = ""
    for key in sorted_keys:
        value = cleaned_params[key]
        if isinstance(value, (dict, list)):
            # 处理对象和数组
            param_string += key + json.dumps(value, separators=(",", ":"))
        else:
            param_string += key + str(value)

    # 3. 拼接固定密钥
    sign_string = "B3978D054A72A7002063637CCDF6B2E5" + param_string

    # 4. 生成MD5签名并转小写
    signature = hashlib.md5(sign_string.encode("utf-8")).hexdigest().lower()

    return signature


def decrypt_response_data(encrypted_data):
    """
    解密响应数据
    """
    try:
        # AES解密参数（从JavaScript代码获取）
        key_hex = "4542343434393733373134453441343038373643453636424534354435393330"
        iv_hex = "42354138393034323039393331383637"
        
        # 将十六进制字符串转换为字节
        key = binascii.unhexlify(key_hex)
        iv = binascii.unhexlify(iv_hex)
        
        # Base64解码加密数据
        encrypted_bytes = base64.b64decode(encrypted_data)
        
        # 创建AES解密器
        cipher = AES.new(key, AES.MODE_CBC, iv)
        
        # 解密数据
        decrypted_bytes = cipher.decrypt(encrypted_bytes)
        
        # 去除PKCS7填充
        decrypted_data = unpad(decrypted_bytes, AES.block_size)
        
        # 转换为UTF-8字符串
        decrypted_text = decrypted_data.decode('utf-8')
        
        # 尝试解析为JSON
        try:
            return json.loads(decrypted_text)
        except json.JSONDecodeError:
            # 如果不是JSON格式，返回原始文本
            return decrypted_text
            
    except Exception as e:
        print(f"解密失败: {e}")
        return None


def make_request(page_no=1, page_size=20, total=2576):
    """
    发送请求并解密响应
    """
    # 请求头
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "Origin": "https://ggzyfw.fj.gov.cn",
        "Pragma": "no-cache",
        "Referer": "https://ggzyfw.fj.gov.cn/business/list/",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
        "sec-ch-ua": '"Microsoft Edge";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
    }

    # Cookies
    cookies = {"ASP.NET_SessionId": "1or2swohq0qx4eqyq05ok0eb"}

    # 请求参数
    current_timestamp = int(time.time() * 1000)  # 当前时间戳（毫秒）

    data = {
        "pageNo": page_no,
        "pageSize": page_size,
        "total": total,
        "AREACODE": "",
        "M_PROJECT_TYPE": "",
        "KIND": "GCJS",
        "GGTYPE": "1",
        "PROTYPE": "",
        "timeType": "6",
        "BeginTime": "2024-12-26 00:00:00",
        "EndTime": "2025-06-26 23:59:59",
        "createTime": "",
        "ts": current_timestamp,
    }

    # 生成签名
    signature = generate_signature(data.copy())  # 使用副本避免修改原数据
    headers["portal-sign"] = signature

    # 打印调试信息
    print(f"时间戳: {current_timestamp}")
    print(f"生成的签名: {signature}")

    # 发送请求
    url = "https://ggzyfw.fj.gov.cn/FwPortalApi/Trade/TradeInfo"
    json_data = json.dumps(data, separators=(",", ":"))

    try:
        response = requests.post(url, headers=headers, cookies=cookies, data=json_data)
        print(f"响应状态码: {response.status_code}")

        if response.status_code == 200:
            response_data = response.json()
            print("原始加密响应:")
            print(json.dumps(response_data, ensure_ascii=False, indent=2))

            # 检查响应是否成功
            if response_data.get("Success") and response_data.get("Data"):
                encrypted_data = response_data["Data"]
                print(f"\n加密数据: {encrypted_data[:100]}...")

                # 解密数据
                decrypted_data = decrypt_response_data(encrypted_data)

                if decrypted_data:
                    print("\n=== 解密成功 ===")
                    if isinstance(decrypted_data, dict):
                        print(json.dumps(decrypted_data, ensure_ascii=False, indent=2))
                    else:
                        print(decrypted_data)
                    return decrypted_data
                else:
                    print("解密失败")
                    return None
            else:
                print("API响应失败或无数据")
                return response_data

        else:
            print(f"请求失败: {response.text}")
            return None

    except Exception as e:
        print(f"请求异常: {e}")
        return None

if __name__ == "__main__":

    print("\n" + "=" * 50 + "\n")

    # 发送请求并解密
    result = make_request(page_no=1, page_size=20)

    if result:
        print("\n=== 最终结果 ===")
        if isinstance(result, dict):
            print(json.dumps(result, ensure_ascii=False, indent=2))
